In this article, we will learn how to create, search, and filter a DropDownList control in Asp.Net as using JavaScript.
Filter and Search ASP.Net DropDownList items using JavaScript
Fist, let start by creating a WebForm, then add controlse to it as shown below:
<div> <asp:TextBox ID="txtFilter" runat="server" onkeyup="FilterDDL(this.value)"></asp:TextBox><br /> <asp:DropDownList ID="ddlColors" runat="server"> <asp:ListItem Text="Black" Value="1"></asp:ListItem> <asp:ListItem Text="Purple" Value="2"></asp:ListItem> <asp:ListItem Text="Red" Value="3"></asp:ListItem> <asp:ListItem Text="Yellow" Value="4"></asp:ListItem> <asp:ListItem Text="Green" Value="5"></asp:ListItem> </asp:DropDownList> </div>
On the window onload event CopyItems method is called. This function populate text and values inside Arrays so we can use them later to filter the DropDownList
CopyItems
var ddlDisplay, ddlValue, ddlCol; function CopyItems() { ddlDisplay = new Array(); ddlValue = new Array(); ddlCol = document.getElementById("<%=ddlColors.ClientID %>"); for (var a = 0; a < ddlCol.options.length; a++) { ddlDisplay[ddlDisplay.length] = ddlCol.options[a].text; ddlValue[ddlValue.length] = ddlCol.options[a].value; } }
Now run this method when the window loads:
window.onload = CopyItems;
FilterItems
The following function is called when keyup event is fired on the search TextBox. This function search for the string and filters the list items.
function FilterDDL(a) { ddlCol.options.length = 0; for (var b = 0; b < ddlDisplay.length; b++) if (ddlDisplay[b].toLowerCase().indexOf(a) != -1) AddItem(ddlDisplay[b], ddlValue[b]); }
AddItem
The AddItem method adds the a new found item to the DropDownList.
function AddItem(a, b) { var c = document.createElement("option"); c.text = a; c.value = b; ddlCol.options.add(c); }
Happy Coding!
Related Articles
Show/Hide Text Box using JavaScript & jQuery
JavaScript Disable browser’s back button in ASP.Net How to get hidden field value using JavaScript
JavaScript Disable browser’s back button in ASP.Net How to get hidden field value using JavaScript
Comments